package leetcode.array;

import java.util.ArrayList;
import java.util.List;

public class NumMatrix {

    List<List<Integer>> map = null;

    public NumMatrix(int[][] matrix) {
        this.map = new ArrayList<>();
        for (int i = 0; i < matrix.length; i++) {
            List<Integer> line = new ArrayList<>();
            for (int j = 0; j < (matrix[i]).length; j++) {
                line.add(sum(matrix, i, j));
            }
            this.map.add(line);
        }
        for (List<Integer> li: this.map) {
            for (Integer i: li) {
                System.out.print(i+", ");
            }
            System.out.println();
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        int tmp_col = col1 - 1;
        int tmp_row = row1 - 1;
        if (tmp_col < 0 && tmp_row < 0) {
            return (this.map.get(row2)).get(col2);
        } else if (tmp_col < 0) {
            return (this.map.get(row2)).get(col2) - (this.map.get(tmp_row)).get(col2);
        } else if (tmp_row < 0) {
            return (this.map.get(row2)).get(col2) - (this.map.get(row2)).get(tmp_col);
        } else {
            return (this.map.get(row2)).get(col2) + (this.map.get(tmp_row)).get(tmp_col)
                    - (this.map.get(tmp_row)).get(col2) - (this.map.get(row2)).get(tmp_col);
        }
    }


    private int sum(int[][] matrix, int x, int y) {
        int sum = 0;
        for (int w = 0; w <= x; w++) {
            for (int k = 0; k <= y; k++) {
                sum += matrix[w][k];
            }
        }
        return sum;
    }

}
